package jp.co.apl.haven_enquete.android.activity;

import java.util.List;
import java.util.Map;

import jp.co.apl.haven.generated.HavenProtos.Answer;
import jp.co.apl.haven.generated.HavenProtos.Category;
import jp.co.apl.haven.generated.HavenProtos.InputType;
import jp.co.apl.haven.generated.HavenProtos.Question;
import jp.co.apl.haven_enquete.android.R;
import jp.co.apl.haven_enquete.android.dao.AnswerDataDao;
import jp.co.apl.haven_enquete.android.dao.QuestionDataDao;
import jp.dev7.android.util.Activities;
import jp.dev7.android.util.Layouts;
import jp.dev7.android.util.Toasts;
import jp.dev7.android.util.Views;
import android.app.ListActivity;
import android.content.ContentUris;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;

public class QuestionList extends ListActivity {

    private ActivityCommon activityCommon = new ActivityCommon(this);

    private QuestionDataDao qDao;

    private AnswerDataDao aDao;

    private int categoryId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

        qDao = new QuestionDataDao(this);
        aDao = new AnswerDataDao(this);

        // TODO あとで消す
        qDao.initDataFile();

        // 前画面から受け取ったData
        Uri uri = getIntent().getData();
        if (uri == null) {
            Toasts.show(this, "不正なパラメータで起動されました");
            finish();
            return;
        }
        categoryId = (int) ContentUris.parseId(uri);
        if (categoryId == -1) {
            Toasts.show(this, "表示するデータが存在しません");
            finish();
            return;
        }

        setup();

        activityCommon.setActionBar("質問一覧");
        Activities.findViewById(this, R.id.actionBar_nextButton).setVisibility(
            View.INVISIBLE);
    }

    private void setup() {
        // 回答情報
        final Map<Integer, Answer> amap = aDao.loadAsMap();

        // トップレベル質問、または回答済みの子質問のみを抽出
        List<Question> listedQuestions = getListedQuestions(categoryId, amap);

        ListAdapter adapter =
            new ArrayAdapter<Question>(
                this,
                R.layout.question_list,
                listedQuestions) {

                @Override
                public View getView(int position, View convertView,
                        ViewGroup parent) {

                    View view =
                        (convertView != null) ? convertView : Layouts.inflate(
                            getContext(),
                            R.layout.question_list);

                    Question question = getItem(position);
                    if (question == null) {
                        return view;
                    }

                    // question title
                    Views.setText(
                        view,
                        R.id.questionList_title,
                        question.getTitle());

                    // answer
                    String answerString = "-";
                    Answer answer = amap.get(question.getId());
                    if (answer != null) {
                        answerString = answer.getAnswer();
                    }
                    if (question.getInputType() == InputType.SELECT
                        || answerString.equals("-")) {

                        Views.setText(
                            view,
                            R.id.questionList_answer,
                            answerString);

                    } else if (question.getInputType() == InputType.NUMBER) {

                        Views.setText(
                            view,
                            R.id.questionList_answer,
                            answerString + question.getUnit());

                    }

                    return view;
                }
            };

        setListAdapter(adapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setup();
    }

    /**
     * 指定カテゴリ中の、トップレベルまたは回答済みの質問のみを抽出する.
     * 
     * @param categoryId
     *            カテゴリID
     * @param answerMap
     *            質問IDをキーとした回答のマップ
     * @return -
     */
    private List<Question> getListedQuestions(int categoryId,
            final Map<Integer, Answer> answerMap) {

        final List<Question> questions =
            qDao.loadAsListByCategoryId(categoryId);

        final Category c = qDao.getCategory(categoryId);

        return Lists.newArrayList(Collections2.filter(
            questions,
            new Predicate<Question>() {
                @Override
                public boolean apply(final Question input) {
                    boolean isTopLevel =
                        Iterables.find(
                            c.getQuestionList(),
                            new Predicate<Question>() {
                                @Override
                                public boolean apply(Question q) {
                                    return q.getId() == input.getId();
                                }
                            },
                            null) != null;
                    return isTopLevel
                        || answerMap.keySet().contains(input.getId());
                }
            }));
    }

    @Override
    protected void onDestroy() {
        activityCommon = null;
        qDao = null;
        aDao = null;
        super.onDestroy();
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Question question = (Question) l.getItemAtPosition(position);

        Intent intent = new Intent(this, Main.class);
        Uri uri = Uri.parse("content://jp.co.apl.haven_enquete/question");
        uri = ContentUris.withAppendedId(uri, question.getId());
        intent.setData(uri);

        startActivity(intent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        return activityCommon.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        return activityCommon.onOptionsItemSelected(item);
    }
}
